<%@ page contentType="text/html;charset=UTF-8"%>
<%@ page import="org.apache.log4j.Logger" %>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
	System.out.println("rbasePath=" + basePath);
%>
<%!
public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
    }
    return ip;
}

%>
<%
Logger rlog = Logger.getLogger(this.getClass());
java.text.SimpleDateFormat rformatter = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
java.util.Date rsnow=new java.util.Date();
String rnow = rformatter.format(rsnow); //将日期时间格局化
String rip=getIpAddr(request);
String rphyPath = application.getRealPath(request.getRequestURI()); //页面对应物理路径
String rreferer = request.getHeader("referer");
rlog.debug("------rrefer="+rreferer);

if (rreferer == null || !rreferer.startsWith("http://"+request.getServerName())){
	System.out.println("---------r非法请求方法---------tempBathPath="+basePath);
	request.setAttribute("loginMess", "非法请求，请通过本系统合法地址进行访问!");

    //记录系统管理操作日志1
    rlog.error("------r非法访问来源："+rreferer);
    rlog.error("------r非法访问时间："+rnow);
    rlog.error("------r非法访问者ip："+request.getRemoteAddr()); // ip 或者 request.getRemoteAddr()
    rlog.error("------r非法访问资源路径："+request.getRequestURI());
    //response.sendRedirect(basePath);
	//request.setAttribute("loginMess", "账号不存在!");
	%>
<script>
	window.parent.parent.location.href="<%=basePath%>";

</script>
	<%//如果上面的js不执行，就执行下面
	response.sendRedirect(basePath);
}
else if(request.getSession().getAttribute("SESSION_USER_CUSTOMER_ID")==null){
	System.out.println("-----------sessionValidate.jsp session 超时，或者非法请求---------------tempBathPath="+basePath);
    //request.getRequestDispatcher("../loginht.jsp").forward(request, response);
    request.setAttribute("loginMess", "会话超时或者您的账号在另一个地方登录，您被迫下线，请重新登录!");
    //记录系统管理操作日志2
    rlog.error("------r访问超时来源："+rreferer);
    rlog.error("------r超时访问时间："+rnow);
    rlog.error("------r超时访问者ip："+request.getRemoteAddr()); // ip 或者 request.getRemoteAddr()
    rlog.error("------r超时访问资源路径："+request.getRequestURI());
	%>
	<script>
		window.parent.location.href="<%=basePath%>";

	</script>
		<%//如果上面的js不执行，就执行下面
		response.sendRedirect(basePath);
}else{

    //记录系统管理操作日志3
    rlog.error("------r访问来源："+rreferer);
    rlog.error("------r访问时间："+rnow);
    rlog.error("------r访问者ip："+ rip ); //ip或者request.getRemoteAddr()
    rlog.error("------r访问资源路径："+ request.getRequestURI());
    //log.error("------访问资源物理路径："+phyPath);
    rlog.error("------r访问者："+request.getSession().getAttribute("SESSION_USER_COMPANY_NAME"));

}
%>

<%
String talkFromCompanyId = request.getParameter("talkFromCompanyId");
String talktoCompanyId = request.getParameter("talktoCompanyId");
String flag = request.getParameter("flag");
if(flag==null){
	flag="";
}
%>
<!DOCTYPE HTML>
<html>
<head>
    <title>会话窗口</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta http-equiv="X-UA-Compatible" content="IE=9">
	<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
    <link rel="stylesheet" href="<%=basePath%>css/my-bootstrap.css" media="screen"  id="tuserskin">
    <link rel="stylesheet" href="<%=basePath%>js/toastr/toastr.css">
    <link rel="stylesheet" href="<%=basePath%>css/bootstrapValidator.min.css">
    <link rel="stylesheet" href="<%=basePath%>css/font-awesome.min.css">
</head>
<body>
<div style="width:50%;height:80%">
<!-- 聊天记录 -->
<div class="panel panel-primary" id="talkContent" style="height:350px;overflow:auto;">
   <table class="table" id="chatContent" name="chatContent">
	   <tr id="cc00"></tr>
	   <tr id="cc01"></tr>
	   <tr id="cc02"></tr>
	   <tr id="cc03"></tr>
	   <tr id="cc04"></tr>
	   <tr id="cc05"></tr>
	   <tr id="cc06"></tr>
	   <tr id="cc07"></tr>
	   <tr id="cc08"></tr>
	   <tr id="cc09"></tr>
	   <tr id="cc10"></tr>

   </table>
   </div>
	<!-- 消息发送窗口 -->
	<form id="chatForm" name="chatForm" action="" method="post">
	<!-- 以下两个为会话双方id -->
	<input type="hidden" name="talk_from" id="talk_from" value="<%=talkFromCompanyId %>">
	<input type="hidden" name="talk_to" id="talk_to" value="<%=talktoCompanyId %>">
	<input type="hidden" name="flag" id="flag" value="<%=flag %>"/>
	<div class="form-group">
	      <textarea id="talk_content" name="talk_content" class="form-control"rows="3"></textarea>
	      <button type="button" onclick="sendMessage();" class="btn btn-default btn-lg ">
	      发送
	   </button>
	   </div>
	</form>
</div>
</body>
</html>
 <script type="text/javascript" src="<%=basePath%>js/jquery-1.8.3.min.js"></script>
    <script type="text/javascript" src="<%=basePath%>js/jquery.cookie.js"></script>
    <script src="<%=basePath%>js/bootstrap.min.js"></script>
	<!--<script src="<%=basePath%>js/jquery-1.10.2/jquery.min.js"></script>
	<script type="text/javascript" src="js/bootstrapValidator.js"></script>-->
	<script src="<%=basePath%>js/bootstrap-paginator.min.js"></script>
	<script src="<%=basePath%>js/respond.js"></script>
	<script src="<%=basePath%>js/html5.js"></script>
	<script src="<%=basePath%>js/toastr/toastr.js"></script>
	<script src="<%=basePath%>js/bootbox.js"></script>
	<script src="<%=basePath%>js/jquery.validate.js"></script>
	<!-- <script src="../js/additional-methods.min.js"></script> -->
	<script src="<%=basePath%>js/my-jquery-curd.js"></script>
	<script src="<%=basePath%>js/tableSortTool.js" ></script>
	<script src="<%=basePath%>js/calendar.js" ></script>
<script type="text/javascript">
$().ready(function(){
	//1、初始化数据显示
	Search(0);
	setInterval('Search(0)',4000);//定时刷新，毫秒；
	//添加回车事件
	$("#talk_content").bind('keypress',function(event){
		if(event.keyCode == "13")
        {
			sendMessage();
        }
	})
}) //end funciton read;

//查询数据函数；
function Search(startIndex){
	//$("#chatContent").html("");
	var condition = "";
	if(1==$("#flag").val()){
		condition = "talk_from=<%=talkFromCompanyId %>&talk_to=<%=talktoCompanyId %>";
	}else{
		condition = $("#chatForm").serialize();
	}

	var url = "<%=basePath%>t_talk/findChatContent?"+condition + "&time=" + Math.random();
	//alert(url);
	$.ajaxSettings.async = false; //设置为同步，否则会有部分数据没出来
	$.getJSON(url, function (data){

		toEmp();
		//1、表格行内容输出
	    $.each(data.items, function(i,item){
	    	$("#cc0"+i).html("");
	    	var str = "";
	    	if(item.talk_fromId==$("#talk_from").val()){//会话发起人
	    		str+="<td  style=\"text-align:right;\"><span style=\"color:#6F8A91\">"+FormatDate(item.talk_time)+"</span><br/><span style=\"font-weight:bold;color:#4D9EB3\">"+doNull(item.talk_from)+"：</span>"+doNull(item.talk_content)+"</td>";
			}else if(item.talk_toId==$("#talk_from").val()){//会话接收人
				str+="<td style=\"text-align:left;\"><span style=\"color:#6F8A91\">"+FormatDate(item.talk_time)+"</span><br/><span style=\"font-weight:bold;color:#4D9EB3\">"+doNull(item.talk_from)+"：</span>"+doNull(item.talk_content)+"</td>";
			}
	    	$("#cc0"+i).append(str);
	    	$("#talkContent").scrollTop($("#talkContent").height());
		});//end each data;
	});
}

//发送新的消息；
function sendMessage(){
	var name = "<%= request.getSession().getAttribute("SESSION_USER_COMPANY_NAME") %>";
	var url = "<%=basePath%>t_talk/saveT_talk?t=1&time="+Math.random();
	var date = new Date();
	var cuurtime = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes();
	//alert(cuurtime);
	$.ajaxSettings.async = false; //设置为同步，否则会有部分数据没出来
	$.ajax({
		cache: true,
		type: "POST",
		url:url,
		data:$('#chatForm').serialize(),// 你的formid
		async: false,
	    error: function(request) {
	        alert("发送失败");
	    },
	    success: function(data) {
	    	//alert("发送成功！");
	    	//var sendStr = $("#talk_content").val();
	    	//var str = "<td  style=\"text-align:right;\"><span style=\"color:#6F8A91\">"+cuurtime+"</span><br/><span style=\"font-weight:bold;color:#4D9EB3\">"+name+"：</span>"+sendStr+"</td>";
	    	//alert(str);
	    	//$("#cc10").val("");
	    	//$("#cc10").append(str);
	    	$("#talk_content").val("");
	    	Search(0);
	    }
	});
}
function toEmp(){
	for(var i=0;i<11;i++){
		$("cc0"+i).html("");
	}
}
function FormatDate (strTime) {
    var date = new Date(strTime);
    return date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()+" "+date.getHours()+":"+date.getMinutes();
}
</script>